package com.hnevc.servicedemo;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    MyServiceConnection connection = new MyServiceConnection();
    //声明一个MyServiceConnection的变量
    MyService.MyBinder myBinder;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    //将在startService按钮被点击的时候调用

    public void buttonClick(View view){
        //启动Service
        int id= view.getId();
        switch (id){
            case R.id.id_btn_start_service:
            {
                Intent intent = new Intent();
                intent.setClass(this,MyService.class);
                startService(intent);
                break;//结束分支
            }
            case R.id.id_btn_stop_service:
            {
                Intent intent = new Intent();
                intent.setClass(this,MyService.class);
                stopService(intent);
                break;//结束分支
            }
            case R.id.id_btn_bind_service:
            {
                Intent intent = new Intent();
                intent.setClass(this,MyService.class);
                //通过bind的方式启动服务，intent意图指定哪一个服务，para2:指代一个bind，
                //
                bindService(intent, connection, BIND_AUTO_CREATE);
                break;
            }
            case  R.id.id_btn_unbind_service:
            {
                unbindService(connection);
                break;

            }
            case R.id.id_btn_bind_play:{
                myBinder.call("PLAY");
                break;
            }
            case R.id.id_btn_bind_pause:{
                myBinder.call("PAUSE");
                break;
            }
            case R.id.id_btn_bind_stop:{
                myBinder.call("STOP");
                break;
            }

            }
        }
        class MyServiceConnection implements ServiceConnection{

            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                myBinder = (MyService.MyBinder) service;


            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                myBinder=null;

            }
        }

    }

